package app.itgungnir.compose.wan.business.main.agenda

import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.outlined.CheckBoxOutlineBlank
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import app.itgungnir.compose.wan.theme.*
import app.itgungnir.compose.wan.widgets.*

@Composable
fun AgendaItem(
    item: Agenda?,
    editCallback: (Agenda) -> Unit,
    deleteCallback: (Agenda) -> Unit,
    toggleCallback: (Agenda) -> Unit
) {
    item ?: return
    WanSwipeMenuCard(
        modifier = Modifier.padding(top = 10.dp),
        menuItems = listOf(
            WanSwipeMenuItem(icon = Icons.Filled.Edit, title = "编辑", backgroundColor = MaterialTheme.colors.secondary) {
                editCallback.invoke(item)
            },
            WanSwipeMenuItem(icon = Icons.Filled.Delete, title = "删除", backgroundColor = MaterialTheme.colors.error) {
                deleteCallback.invoke(item)
            }
        )
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {
            WanTitle(content = item.title)
            Spacer(modifier = Modifier.height(2.dp))
            Row(modifier = Modifier.fillMaxWidth()) {
                Column(modifier = Modifier.weight(1F)) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        val statusPair = when (item.status) {
                            1 -> "已完成" to GreenPalette.lightPrimaryColor
                            else -> "未完成" to Color.DarkGray
                        }
                        WanTagButton(
                            modifier = Modifier.padding(end = 5.dp),
                            text = statusPair.first,
                            color = statusPair.second
                        )
                        val typePair = when (item.type) {
                            1 -> "工作" to BluePalette.lightPrimaryColor
                            2 -> "生活" to PinkPalette.lightPrimaryColor
                            else -> "娱乐" to TealPalette.lightPrimaryColor
                        }
                        WanTagButton(
                            modifier = Modifier.padding(end = 5.dp),
                            text = typePair.first,
                            color = typePair.second
                        )
                        val priorityPair = when (item.priority) {
                            1 -> "重要" to RedPalette.lightPrimaryColor
                            else -> "一般" to OrangePalette.lightPrimaryColor
                        }
                        WanTagButton(text = priorityPair.first, color = priorityPair.second)
                    }
                    Spacer(modifier = Modifier.height(2.dp))
                    WanDescription(content = item.content)
                    Spacer(modifier = Modifier.height(2.dp))
                    WanInfo(content = item.dateStr, prefix = "创建日期：")
                    WanInfo(content = item.completeDateStr, prefix = "完成日期：")
                }
                WanIconButton(
                    modifier = Modifier.align(Alignment.Bottom),
                    icon = if (item.status == 1) Icons.Filled.CheckBox else Icons.Outlined.CheckBoxOutlineBlank,
                    color = when (item.status == 1) {
                        true -> GreenPalette.lightPrimaryColor
                        else -> MaterialTheme.colors.onBackground.copy(alpha = 0.2F)
                    }
                ) {
                    toggleCallback.invoke(item.copy(status = 1 - item.status))
                }
            }
        }
    }
}

@Composable
fun AgendaFilter(
    statusValueState: MutableState<Int?> = mutableStateOf(null),
    typeValueState: MutableState<Int?> = mutableStateOf(null),
    priorityValueState: MutableState<Int?> = mutableStateOf(null),
    orderByValueState: MutableState<Int?> = mutableStateOf(4),
    onConditionChanged: () -> Unit = {}
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(color = MaterialTheme.colors.background),
        verticalAlignment = Alignment.CenterVertically
    ) {
        val statusSelectState = remember { mutableStateOf(false) }
        AgendaFilterItem(
            modifier = Modifier.weight(1F),
            title = "状态",
            selectState = statusSelectState,
            choicePairs = listOf("全部" to null, "已完成" to 1, "未完成" to 0),
            valueState = statusValueState,
            onConditionChanged = onConditionChanged
        )
        WanDivider(height = 20.dp)
        val typeSelectState = remember { mutableStateOf(false) }
        AgendaFilterItem(
            modifier = Modifier.weight(1F),
            title = "类型",
            selectState = typeSelectState,
            choicePairs = listOf("全部" to null, "工作" to 1, "生活" to 2, "娱乐" to 3),
            valueState = typeValueState,
            onConditionChanged = onConditionChanged
        )
        WanDivider(height = 20.dp)
        val prioritySelectState = remember { mutableStateOf(false) }
        AgendaFilterItem(
            modifier = Modifier.weight(1F),
            title = "优先级",
            selectState = prioritySelectState,
            choicePairs = listOf("全部" to null, "重要" to 1, "一般" to 2),
            valueState = priorityValueState,
            onConditionChanged = onConditionChanged
        )
        WanDivider(height = 20.dp)
        val orderBySelectState = remember { mutableStateOf(false) }
        AgendaFilterItem(
            modifier = Modifier.weight(1F),
            title = "排序",
            selectState = orderBySelectState,
            choicePairs = listOf("创建日期逆序" to 4, "创建日期顺序" to 3, "完成日期逆序" to 2, "完成日期顺序" to 1),
            valueState = orderByValueState,
            onConditionChanged = onConditionChanged
        )
    }
}

@Composable
private fun AgendaFilterItem(
    modifier: Modifier = Modifier,
    title: String,
    selectState: MutableState<Boolean>,
    choicePairs: List<Pair<String, Int?>>,
    valueState: MutableState<Int?>,
    onConditionChanged: () -> Unit = {}
) {
    Column(
        modifier = modifier
            .fillMaxWidth()
            .clickable { selectState.value = true }
            .padding(start = 5.dp, end = 5.dp, top = 10.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        val selectTint = if (selectState.value) MaterialTheme.colors.primary else MaterialTheme.colors.onBackground
        val firstItemSelected = choicePairs.indexOfFirst { it.second == valueState.value } <= 0
        WanDescription(
            content = title,
            color = selectTint,
            style = MaterialTheme.typography.subtitle2.copy(fontWeight = FontWeight.Bold)
        )
        Spacer(modifier = Modifier.height(3.dp))
        WanInfo(
            content = choicePairs.firstOrNull { it.second == valueState.value }?.first,
            color = if (!firstItemSelected) MaterialTheme.colors.primary else MaterialTheme.colors.onBackground
        )
        Spacer(modifier = Modifier.height(5.dp))
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(5.dp)
                .background(if (selectState.value) MaterialTheme.colors.primary else MaterialTheme.colors.background)
        )
    }
    DropdownMenu(
        modifier = Modifier
            .fillMaxWidth()
            .background(color = MaterialTheme.colors.background),
        expanded = selectState.value,
        onDismissRequest = { selectState.value = false }
    ) {
        choicePairs.forEach { choice ->
            val choiceSelected = valueState.value == choice.second
            DropdownMenuItem(
                modifier = Modifier.fillMaxWidth(),
                onClick = {
                    if (valueState.value != choice.second) {
                        valueState.value = choice.second
                        onConditionChanged.invoke()
                    }
                    selectState.value = false
                }
            ) {
                WanDescription(
                    modifier = Modifier.weight(1F),
                    content = choice.first,
                    color = if (choiceSelected) MaterialTheme.colors.primary else MaterialTheme.colors.onBackground
                )
                if (choiceSelected) {
                    Icon(imageVector = Icons.Filled.Check, contentDescription = "", tint = MaterialTheme.colors.primary)
                }
            }
        }
    }
}

@Composable
fun ColumnScope.AgendaDialogUI(
    activity: AppCompatActivity,
    origin: Agenda? = null,
    loadingState: State<Boolean> = mutableStateOf(false),
    errorState: State<Throwable?> = mutableStateOf(null),
    callback: (String, String, String?, Int?, Int?) -> Unit
) {
    val focusManager = LocalFocusManager.current
    val titleValue = remember { mutableStateOf(TextFieldValue(text = origin?.title ?: "")) }
    val contentValue = remember { mutableStateOf(TextFieldValue(text = origin?.content ?: "")) }
    val priorityValue = remember { mutableStateOf(origin?.priority) }
    val typeValue = remember { mutableStateOf(origin?.type) }
    val dateValue = remember { mutableStateOf(origin?.run { date to dateStr }) }
    WanTitle(
        modifier = Modifier.align(Alignment.CenterHorizontally),
        content = if (origin == null) "新增待办信息" else "修改待办信息"
    )
    Spacer(modifier = Modifier.height(5.dp))
    WanOutlinedInput(state = titleValue, label = "标题", icon = Icons.Filled.Title, loadingState = loadingState)
    Spacer(modifier = Modifier.height(5.dp))
    WanOutlinedInput(state = contentValue, label = "内容", icon = Icons.Filled.Event, loadingState = loadingState)
    Spacer(modifier = Modifier.height(10.dp))
    WanRadioButtonGroup(
        modifier = Modifier.padding(start = 10.dp),
        icon = Icons.Filled.Tour,
        selectedValueState = priorityValue,
        choicePairs = listOf("一般" to 2, "重要" to 1),
        loadingState = loadingState
    )
    Spacer(modifier = Modifier.height(10.dp))
    WanRadioButtonGroup(
        modifier = Modifier.padding(start = 10.dp),
        icon = Icons.Filled.TurnedIn,
        selectedValueState = typeValue,
        choicePairs = listOf("工作" to 1, "生活" to 2, "娱乐" to 3),
        loadingState = loadingState
    )
    Spacer(modifier = Modifier.height(10.dp))
    WanDatePickDialog(
        modifier = Modifier.padding(start = 10.dp),
        activity = activity,
        selectedDateValue = dateValue,
        loadingState = loadingState
    )
    Spacer(modifier = Modifier.height(20.dp))
    WanButton(
        modifier = Modifier.fillMaxWidth(),
        text = if (origin == null) "确认新增" else "确认修改",
        loadingState = loadingState
    ) {
        focusManager.clearFocus()
        callback.invoke(
            titleValue.value.text,
            contentValue.value.text,
            dateValue.value?.second,
            priorityValue.value,
            typeValue.value
        )
    }
    WanError(modifier = Modifier.padding(top = 5.dp), contentState = errorState)
}

@Preview(name = "AgendaDialogUI light mode", showBackground = false)
@Preview(name = "AgendaDialogUI dark mode", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = false)
@Composable
private fun AgendaDialogUIPreview() {
    WanDialogPreview {
        AgendaDialogUI(activity = AppCompatActivity()) { _, _, _, _, _ -> }
    }
}
